$(document).ready( function() {
    //An example with all options.
     var waTable = $('#listPanel').WATable({
        pageSize: 8,                //Sets the initial pagesize
        filter: true,               //Show filter fields
        columnPicker: true,         //Show the columnPicker button
        pageSizes: [1,5,8,12,200],  //Set custom pageSizes. Leave empty array to hide button.
        hidePagerOnEmpty: true,     //Removes the pager if data is empty.
        preFill: true,              //Initially fills the table with empty rows (as many as the pagesize).
        //url: '/someWebservice'    //Url to a webservice if not setting data manually as we do in this example
        //urlData: { report:1 }     //Any data you need to pass to the webservice
        //urlPost: true             //Use POST httpmethod to webservice. Default is GET.
        types: {                    //Following are some specific properties related to the data types
            string: {
                //tooltip: "Giggedi...",      //What to say in tooltip when hoovering filter fields. Leave a space to remove default tooltip.
                placeHolder: "type here... "  //What to say in the filter fields. Leave a space to have no text.
            },
            number: {
                decimals: 1   //Sets decimal precision for float types
            },
            bool: {
                //tooltip: " "
            },
            date: {
              utc: true,            //Show time as universal time, ie without timezones.
              //format: 'yy/dd/MM',   //The format. See all possible formats here http://arshaw.com/xdate/#Formatting.
              datePicker: true      //Requires "Datepicker for Bootstrap" plugin (http://www.eyecon.ro/bootstrap-datepicker).
            }
        },
        actions: {                //This generates a button where you can add elements.
            filter: true,         //If true, the filter fields can be toggled visible and hidden.
            columnPicker: true,   //if true, the columnPicker can be toggled visible and hidden.
            custom: [             //Add any other elements here. Here is a refresh and export example.
              $('<a href="#" class="refresh"><i class="icon-refresh"></i>&nbsp;Refresh</a>'),
              $('<a href="#" class="export_all"><i class="icon-share"></i>&nbsp;Export all rows</a>'),
              $('<a href="#" class="export_checked"><i class="icon-share"></i>&nbsp;Export checked rows</a>'),
              $('<a href="#" class="export_filtered"><i class="icon-share"></i>&nbsp;Export filtered rows</a>')
            ]
        },
        tableCreated: function(data) {    //Fires when the table is created / recreated. Use it if you want to manipulate the table in any way.
            console.log('table created'); //data.table holds the html table element.
            console.log(data);            //'this' keyword also holds the html table element.
        },
        rowClicked: function(data) {      //Fires when a row is clicked (Note. You need a column with the 'unique' property).
            console.log('row clicked');   //data.event holds the original jQuery event.
            console.log(data);            //data.row holds the underlying row you supplied.
                                          //data.column holds the underlying column you supplied.
                                          //data.checked is true if row is checked.
                                          //'this' keyword holds the clicked element.
            if ( $(this).hasClass('userId') ) {
              data.event.preventDefault();
              alert('You clicked typeId: ' + data.row.typeId);
            }
        },
        columnClicked: function(data) {    //Fires when a column is clicked
          console.log('column clicked');  //data.event holds the original jQuery event
          console.log(data);              //data.column holds the underlying column you supplied
                                          //data.descending is true when sorted descending (duh)
        },
        pageChanged: function(data) {      //Fires when manually changing page
          console.log('page changed');    //data.event holds the original jQuery event
          console.log(data);              //data.page holds the new page index
        },
        pageSizeChanged: function(data) {  //Fires when manually changing pagesize
          console.log('pagesize changed');//data.event holds teh original event
          console.log(data);              //data.pageSize holds the new pagesize
        }
    }).data('WATable');  //This step reaches into the html data property to get the actual WATable object. Important if you want a reference to it as we want here.

    //Generate some data
    var data = initData(waTable);
    //waTable.setData(data);  //Sets the data.
    //waTable.setData(data, true); //Sets the data but prevents any previously set columns from being overwritten
    //waTable.setData(data, false, false); //Sets the data and prevents any previously checked rows from being reset

    var allRows = waTable.getData(false); //Gets the data you previously set.
    var checkedRows = waTable.getData(true); //Gets the data you previously set, but with checked rows only.
    var filteredRows = waTable.getData(false, true); //Gets the data you previously set, but with filtered rows only.

    var pageSize = waTable.option("pageSize"); //Get option
    //waTable.option("pageSize", pageSize); //Set option

    //Example event handler triggered by the custom refresh link above.
    $('body').on('click', '.refresh', function(e) {
        e.preventDefault();
        var data = getData();
        waTable.setData(data);
    });
    //Example event handler triggered by the custom export links above.
    $('body').on('click', '.export_checked, .export_filtered, .export_all', function(e) {
        e.preventDefault();
        var elem = $(e.target);
        var data;
        if (elem.hasClass('export_all')) data = waTable.getData(false);
        else if (elem.hasClass('export_checked')) data = waTable.getData(true);
        else if (elem.hasClass('export_filtered')) data = waTable.getData(false, true);
        console.log(data.rows.length + ' rows returned');
        console.log(data);
        alert(data.rows.length + ' rows returned.\nSee console for details.');
    });
});
function initData(waTable) {

    //First define the columns
    var cols = {
        typeId: {
            index: 1, //The order this column should appear in the table
            type: "number", //The type. Possible are string, number, bool, date(in milliseconds).
            friendly: "<i class='icon-user'></i>",  //Name that will be used in header. Can also be any html as shown here.
            format: "<a href='#' class='userId' target='_blank'>{0}</a>",  //Used to format the data anything you want. Use {0} as placeholder for the actual data.
            unique: true  //This generates a checkbox to each row. Be certain the values are really unique or weird things will happen.
        },
        typeName: {
            index: 2,
            type: "string",
            friendly: "typeName",
            tooltip: "Some explanation here..." //Help text for this column that is visible when hoovering the generated icon.
        },
        createBy: {
            index: 3,
            type: "number",
            friendly: "createBy",
            tooltip: "Some explanation here...",
            filter: false //Removes filter field for this column
        },
        belongTo: {
            index: 4,
            decimals: 2, //Force decimal precision
            type: "number",
            friendly: "belongTo"
        },
        parentId: {
            type: "number",
            friendly: "parentId",
            hidden:true //Hides the column. Useful if you want this value later on but no visible to user. It's available to be unhidden if columnPicker is enabled.
        },
        isRoot: {
            index: 5,
            type: "bool",
            friendly: "isRoot"
        },
        createOn: {
            index: 6,
            type: "date", //Don't forget dates are expressed in milliseconds
            friendly: "createOn",
            sortOrder: "desc" //Data will initially be sorted by this column. Possible are "asc" or "desc"
        },
        path : {
        	index : 7,
        	type : 'string',
        	friendly : 'Path'
        },
        typeKey : {
        	index : 8,
        	type : 'string',
        	friendly : 'Type Key'
        }
    };
    /*
      Create the actual data.
      Whats worth mentioning is that you can use a 'format' property just as in the column definition,
      but on a row level. See below on how we create a weightFormat property. This will be used when rendering the weight column.
      Also, you can pre-check rows with the 'checked' property and prevent rows from being checkable with the 'checkable' property.
    */
    
    //Create the returning object. Besides cols and rows, you can also pass any other object you would need later on.
    $.ajax({
		url: __ctxPath+'/system/json_get_type_list.do',
		type : 'POST',
		success: function (result) {
			console.info(result);
			var rows = eval('('+result+')');
			 var data = {
		        cols: cols,
		        rows: rows,
		        otherStuff: {
		            thatImight: 1,
		            wantLater: true
		        }
		    };
			waTable.setData(data);
		}
	});
    //return data;
}

//-- watable end
//
var chosenfield = $(".chzn-select-deselect").chosen({allow_single_deselect:true});
chosenfield.change(function(){
	$('#type_tree').empty();
	initTree();
});

$.ajax({
	url: __ctxPath+'/system/json_get_type_tree.do',
	type : 'POST',
	success: function (data) {
		initTreeView(data);
	}
});
function initTreeView(data){
	var _data = eval('('+data+')'),appendStr,children;
	if(_data){
		appendStr = '<ul><li><i id="cursor" class="icon-play"></i><a id="'+_data.id+'">'+_data.text+'</a>';
		children = _data.children;
		appendStr = appendChildren(appendStr,children);
		appendStr += '</li></ul>';
		$('#type_tree').append(appendStr);
		
		$('#type_tree a').bind('click',function(){
			$(this).before($('#cursor'));
		});
	}
}
function appendChildren(appendStr,children){
	if(children && children.length>0){
		appendStr +='<ul>';
		for(var i=0;i<children.length;i++){
			appendStr +='<li><a id="'+children[i].id+'">'+children[i].text+'</a>';
			gChildren = children[i].children;
			if(gChildren && gChildren.length>0){
				appendStr = appendChildren(appendStr,gChildren);
			}
			appendStr +='</li>';
		}
		appendStr +='</ul>';
	}
	return appendStr;
}
function initTree(){
	var rootId = $(".chzn-select-deselect").val();
	$.ajax({
		url: __ctxPath+'/system/json_get_type_tree.do',
		type : 'POST',
		data : {rootId : rootId},
		success: function (data) {
			initTreeView(data);
		}
	});
}